from django.shortcuts import render, redirect, get_object_or_404

from .models import Student, ClassName


# Create your views here.
def index(request):
    students = Student.objects.order_by('study_time').all()
    return render(request, 'classmate/index.html', {'students': students})


def detail(request, student_id):
    try:
        student = Student.objects.get(pk=student_id)
    except Student.DoesNotExist:
        student = {}
    return render(request, 'classmate/detail.html', {'student': student})


def add_student(request):
    if request.method == 'GET':
        classname = ClassName.objects.all()
        return render(request, 'classmate/add.html', {'classname': classname})

    if request.method == 'POST':
        name = request.POST.get('name')
        gender = request.POST.get('gender')
        age = request.POST.get('age')
        study_time = request.POST.get('study_time')
        class_name_id = request.POST.get('class_name_id')

        new_student = Student(name=name, gender=gender, age=age, study_time=study_time, class_name_id=class_name_id)
        new_student.save()
        return redirect("classmate:index")

def add_class(request):
    if request.method == 'GET':
        classname = ClassName.objects.all()
        return render(request, 'classmate/addClass.html', {'classname': classname})

    if request.method == 'POST':
        name = request.POST.get('name')
        pub_date = request.POST.get('pub_date')

        new_class = ClassName(name=name, pub_date=pub_date)
        new_class.save()
        return redirect("classmate:class_list")

def class_list(request):
    classname = ClassName.objects.all()
    return render(request, 'classmate/classlist.html', {'classname': classname})

def search_student(request):
    if request.method == 'GET':
        name = request.GET.get('name')
        try:
            student = Student.objects.get(name__icontains=name)
        except Student.DoesNotExist:
            student = {}
        return render(request, 'classmate/detail.html', {'student': student})

def edit_info(request, student_id):
    if request.method == 'GET':
        student = get_object_or_404(Student, pk=student_id)
        classname = ClassName.objects.all()
        return render(request, 'classmate/edit.html', {'student': student, 'classname':classname})

    if request.method == 'POST':
        update_student = get_object_or_404(Student, pk=student_id)
        update_student.name = request.POST.get('name')
        update_student.age = request.POST.get('age')
        update_student.gender = request.POST.get('gender')
        update_student.study_time = request.POST.get('study_time')
        update_student.class_name_id = request.POST.get('class_name_id')
        update_student.save()
        return redirect("classmate:detail", student_id)
